<?php
/**
 * Author: ChenGuangHui
 * Email：13035809409@163.com
 * Date Time: 2021/5/13 16:52
 */

namespace App\Logic\Goods;


use App\Enums\HttpCode;
use App\Logic\CommLogic;
use Illuminate\Database\Eloquent\Builder;
use App\Models\BlindBox;
use App\Models\Store\BlindBoxRule;
use Exception;
use Illuminate\Database\QueryException;
use Illuminate\Support\Arr;

class BlindBoxLogic extends CommLogic
{
    
    /**
     * @param $params
     * @return mixed
     */
    public function lists($params)
    {
        $query = BlindBox::query()
            ->when(isset($params['status']), function (Builder $query) use ($params) {
                $query->where('status', $params['status']);
            })
            ->when(!empty($params['name']), function (Builder $query) use ($params) {
                $query->where('name', 'like', '%' . $params['name'] . '%');
            });

        if (!empty($sortData)) {
            $query = $query->orderBy($sortData['sortRow'], $sortData['sortType']);
        }else{
            $query = $query->orderBy('id', 'desc');
        }

        $data = $query->get()->toArray();
        foreach($data as &$item){
            $item['thumb'] = Arr::first(array_column(json_decode($item['thumb'], true), 'url'));
        }
        return $data;
    }

    /**
     * @param array $where
     * @param array $pageData
     * @param array $sortData
     * @return \Illuminate\Http\JsonResponse
     */
    public function index($where = [], $pageData = ['pageSize' => 20, 'pageNow' => 1], $sortData = [])
    {
        $query = BlindBox::query()
            ->when(isset($where['status']), function (Builder $query) use ($where) {
                $query->where('status', $where['status']);
            })
            ->when(!empty($where['name']), function (Builder $query) use ($where) {
                $query->where('name', 'like', '%' . $where['name'] . '%');
            });

        if (!empty($sortData)) {
            $query = $query->orderBy($sortData['sortRow'], $sortData['sortType']);
        }else{
            $query = $query->orderBy('id', 'desc');
        }
        $data = $query->paginate($pageData['pageSize'], ['*'], 'page', $pageData['pageNow'])->toArray();
        
        foreach($data['data'] as &$item){
            $item['thumb'] = Arr::first(array_column(json_decode($item['thumb'], true), 'url'));
        }
        return $data;
    }

    /**
     * @param $params
     * @return \App\Models\Model|\Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model
     */
    public function store($params)
    {
        $lockName = 'blind_box_store_' . auth('api')->id();
        $lock = \Cache::lock($lockName, 5);
        abort_if(!$lock->get(), HttpCode::TOO_MANY_REQUESTS, '请勿重复操作！');
        \DB::beginTransaction();
        try {
            $data = array(
                'title' => $params['title'] ?? '',
                'price' => $params['price'],
                'status' => $params['status'] ?? 0,
                'sort' => $params['sort'] ?? 0,
                'thumb' => json_encode($params['thumb'], true),
                'content' => $params['content'] ?? '',
                'md_content' => $params['md_content'] ?? '',
            );
            $blindBox = BlindBox::query()->create($data);
            foreach($params["product"] as $item){
                $data = array(
                    'blind_box_id' => $blindBox->getQueueableId(),
                    'goods_id' => $item['goods_id'],
                    'title' => $item['title'],
                    'rule_type' => $item['rule_type'],
                    'goods_name' => $item['goods_name'],
                    'goods_price' => $item['goods_price'],
                    'goods_thumb' => $item['goods_thumb']
                );
                BlindBoxRule::query()->create($data);
            }
            \DB::commit();
        } catch (QueryException $exception) {
            \DB::rollBack();
            throw new Exception($exception->getMessage(), $exception->getCode());
        }
        return true;
    }

    /**
     * @param $blindBoxId
     * @return \App\Models\Model|\Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|object|null
     */
    public function show($data, $blind_boxId)
    {
        $data = BlindBox::query()->where('id', $blind_boxId)->first();
        abort_if(empty($data), HttpCode::FORBIDDEN, '盲盒不存在！');
        $blind_boxInfo = $data->toArray();
        $blind_boxInfo['thumb'] = json_decode($blind_boxInfo['thumb'], true);
        $blind_boxInfo['product'] = BlindBoxRule::query()->where('blind_box_id', $blind_boxInfo['id'])->get();
        return $blind_boxInfo;
    }

    /**
     * @param $params
     * @param $blind_boxId
     * @return bool|int
     */
    public function update($params, $blind_boxId)
    {
        $lockName = 'blind_box_update_' . auth('api')->id();
        $lock = \Cache::lock($lockName, 5);
        abort_if(!$lock->get(), HttpCode::TOO_MANY_REQUESTS, '请勿重复操作！');
        \DB::beginTransaction();
        try {
            $data = array(
                'title' => $params['title'] ?? '',
                'price' => $params['price'],
                'status' => $params['status'] ?? 0,
                'sort' => $params['sort'] ?? 0,
                'thumb' => json_encode($params['thumb'], true),
                'content' => $params['content'] ?? 0,
                'md_content' => $params['md_content'] ?? 0,
            );
            BlindBox::query()->where('id', $blind_boxId)->update($data);
            BlindBoxRule::query()->where('blind_box_id', $blind_boxId)->whereNotIn('goods_id', array_column($params["product"], 'goods_id'))->delete();
            foreach($params["product"] as $item){
                $data = array(
                    'blind_box_id' => $blind_boxId,
                    'goods_id' => $item['goods_id'],
                    'rule_type' => $item['rule_type'],
                    'goods_name' => $item['goods_name'],
                    'title' => $item['title'],
                    'goods_price' => $item['goods_price'],
                    'goods_thumb' => $item['goods_thumb']
                );
                $rule = BlindBoxRule::query()->where('blind_box_id', $blind_boxId)->where('goods_id', $item['goods_id'])->first();
                if (empty($rule)) {
                    BlindBoxRule::query()->create($data);
                }else{
                    BlindBoxRule::query()->where('blind_box_id', $blind_boxId)->where('goods_id', $item['goods_id'])->update($data);
                }
            }
            
            \DB::commit();
        } catch (QueryException $exception) {
            \DB::rollBack();
            throw new Exception($exception->getMessage(), $exception->getCode());
        }
        return true;
    }

    /**
     * @param $blind_boxId
     * @return bool|mixed|null
     */
    public function destroy($blind_boxId)
    {
        $data = BlindBox::query()->where('id', $blind_boxId)->first();
        abort_if(empty($data), HttpCode::FORBIDDEN, '盲盒不存在！');
        return BlindBox::query()->where('id', $blind_boxId)->delete();
    }
}
